package com.wesley.singleton;


/**
 * <h1>Double check</h1>
 *
 * <p>
 *     定义一个 volatile 变量 ，让变量主存可见
 *     在进入第一个if判断时候，添加同步代码块。
 * </p>
 */
public class SingletonTest4 {

    // 测试方法
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                Singleton4 instance = Singleton4.getInstance();
                System.out.println(Thread.currentThread().getName() + "---instance.hashCode():" + instance.hashCode());
            }).start();

        }
    }
}

class Singleton4 {
    private static volatile Singleton4 instance;

    private Singleton4() {
    }

    public static Singleton4 getInstance() {
        if (instance == null) {
            synchronized (Singleton4.class) {
                if (instance == null) {
                    instance = new Singleton4();
                }
            }
        }
        return instance;
    }
}
